package com.spring.security.validate.code;

import com.spring.security.validate.code.sms.SmsCodeSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @ClassName ValicateCodeController
 * @Description ValicateCodeController
 * @Author 朱秒
 * @Date 2020/2/23 21:53
 * @Version 1.0
 */
@RestController
public class ValidateCodeController {
    public static final String SESSION_IMAGE_KEY = "SESSION_KEY_IMAGE_CODE";
    public static final String SESSION_SMS_KEY = "SESSION_KEY_SMS_CODE";
    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
    /*@Autowired
    private ValidateCodeGenerator imageCodeGenerator;
    @Autowired
    private ValidateCodeGenerator smsCodeGenerator;*/
    @Autowired
    private Map<String, ValidateCodeGenerator> validateCodeGenerators;

    @Autowired
    private SmsCodeSender smsCodeSender;
    @GetMapping("/code/image")
    public void createValidateCodeImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ImageCode imageCode = (ImageCode) validateCodeGenerators.get("imageValidateCodeGenerator").generatorCode(request);
        sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_IMAGE_KEY, imageCode);
        ImageIO.write(imageCode.getImage(),"JPEG", response.getOutputStream());
    }

    @GetMapping("/code/sms")
    public void createValidateCodeSms(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletRequestBindingException {
        ValidateCode smsCode = validateCodeGenerators.get("smsValidateCodeGenerator").generatorCode(request);
        sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_SMS_KEY, smsCode);
        //发送验证码给手机
        String moblie = ServletRequestUtils.getRequiredStringParameter(request, "mobile");
        smsCodeSender.sendSmsCode(moblie, smsCode.getCode());
    }
}
